<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input placeholder="请输入标题" :disabled="formDisabled" v-model="model.bpmBizTitle"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <a-input v-model="model.createTime" placeholder="请输入申请时间" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep :multi="false" v-model="model.proposer" disabled></select-user-by-dep>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart v-model="model.proposerDeptId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请金额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyMoney">
              <a-input-number :disabled="formDisabled" :max="99999999" :min="0"  v-model="model.applyMoney" placeholder="请输入申请金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="调拨分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotType">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.allotType" dictCode="allot_type" placeholder="请选择调拨分类"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="使用日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usedDate">
              <j-date :disabled="formDisabled" placeholder="请选择使用日期" v-model="model.usedDate"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="预计归还日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="anticipateReturnDate">
              <j-date :disabled="formDisabled" placeholder="请选择预计归还日期" v-model="model.anticipateReturnDate"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="资金用途" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purpose">
              <a-textarea :disabled="formDisabled" :max-length="100" v-model="model.purpose" rows="2" placeholder="请输入资金用途"/>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col> -->
        </a-row>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="调出信息">
          <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="调出公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotOutUnit">
              <select-Company-input :disabled="formDisabled" v-model="model.allotOutUnit" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="调出团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotOutTeam">
              <select-team-input
                  :disabled="formDisabled"
                  v-model="model.allotOutTeam" :tdlx="3"/>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="调出日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotOutDate">
              <a-date-picker :disabled=formDisabled placeholder="请选择调出时间" v-model="model.allotOutDate" format="YYYY-MM-DD" @change="onAllotOutDateChange" style="width: 100%;" />
            </a-form-model-item>
          </a-col> -->
          </a-row>
          </a-collapse-panel>

          <a-collapse-panel key="3" header="调入信息">
          <a-row :gutter="48">
            <a-col :span="12">
            <a-form-model-item label="调入公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotInUnit">
              <select-Company-input :disabled="formDisabled" v-model="model.allotInUnit" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="调入团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotInTeam">
                  <select-team-input
                  :disabled="formDisabled"
                  v-model="model.allotInTeam" :tdlx="3"/>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
          <a-form-model-item label="调入日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="allotInDate">
            <a-date-picker :disabled=formDisabled placeholder="请选择调入时间" v-model="model.allotInDate" format="YYYY-MM-DD" @change="onAllotInDateChange" style="width: 100%;" />
            </a-form-model-item>
          </a-col> -->
        </a-row>
        </a-collapse-panel>
        <a-collapse-panel key="4" header="附件信息">
            <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload :disabled="formDisabled" v-model="model.attachment"></j-upload>
            </a-form-model-item>
          </a-col>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-row>
      </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 20px"></common-flow-list>
    </j-form-container>
    <!-- <a-row :gutter="48" v-if="formBpm">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" @click="onPrint">打印</a-button>
      </a-col>
    </a-row> -->
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpCapitalAllotFormPrint v-if="formBpm" class="print_style" id="capitalContent" :formData="model" :formDataHistory="formData"></ErpCapitalAllotFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import ErpCapitalAllotFormPrint from './ErpCapitalAllotFormPrint' // 打印
  export default {
    name: 'ErpCapitalAllotForm',
    components: {
      SelectTeamInput,
      SelectPersonInput,
      SelectUserByDep,
      CommonFlowList,
      SelectCompanyInput,
      ErpCapitalAllotFormPrint
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      //迭代14调整 财务要求可以同一个团队 调出团队和调入团队可以同一个 调整方案：以下代码注释掉
      // var validatorTeam = async (rule,value,callback)=>{
      //   if(value){
      //     const that = this;
      //     if(that.model.allotOutTeam == that.model.allotInTeam) {
      //       callback('调出团队和调入团队不能为同一团队！')
      //       return;
      //     }
      //     callback()
      //   }
      //   callback()
      // };
      var validatorInOrOutDate = async (rule,value,callback)=>{
        if(value){
          const that = this;
          if(Date.parse(that.model.allotInDate) < Date.parse(that.model.allotOutDate)) {
            callback('调入时间不能早于调出时间！')
            return;
          }
          callback()
        }
        callback()
      };
      var validatorDate = async (rule,value,callback)=>{
        if(value){
          const that = this;
          if( Date.parse(that.model.anticipateReturnDate) <  Date.parse(that.getDate(that.model.createTime))){
            callback('预计归还日期日期不能早于申请日期!')
            return;
          }
          callback()
        }
        callback()
      };
      return {
        allotInDate: null, // 调入时间
        allotOutDate: null, // 调出时间
        model:{
          allotOutDate: undefined,
          allotInDate: undefined
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        activeKey: ['1','2','3','4'],
        confirmLoading: false,
        validatorRules: {
        proposer: [
            { required: true, message: '请选择申请人!',trigger: 'change'},
        ],
        proposerDeptId: [
            { required: true, message: '请选择申请部门!',trigger: 'change'},
        ],
        createTime: [
            { required: true, message: '请选择申请时间!',trigger: 'change'},
        ],
        applyMoney: [
            { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额！!' },
        ],
        allotType: [
            { required: true, message: '请选择调拨分类!',trigger: 'change'},
        ],
        usedDate: [
            { required: true, message: '请选择使用日期!',trigger: 'change'},
        ],
        anticipateReturnDate: [
            { required: true, message: '请选择预计归还日期!',trigger: 'change'},
            // { validator: validatorDate, trigger: "change" },
        ],
        teamId: [
            { required: true, message: '请选择所属团队!',trigger: 'change'},
        ],
        purpose: [
            { required: true, message: '请输入资金用途!',trigger: 'blur'},
        ],
        allotOutUnit: [
            { required: true, message: '请选择调出公司!',trigger: 'change' },
        ],
        allotOutTeam: [
            { required: true, message: '请选择调出团队!',trigger: 'change'},
          //迭代14调整 财务要求可以同一个团队 调出团队和调入团队可以同一个 调整方案：以下代码注释掉
            // { validator: validatorTeam, trigger: "change" },
        ],
        allotOutDate: [
            { required: true, message: '请选择调出时间!',trigger: 'change' },
        ],
        allotInUnit: [
            { required: true, message: '请选择调入公司!',trigger: 'change' },
        ],
        allotInTeam: [
            { required: true, message: '请选择调入团队!',trigger: 'change' },
          //迭代14调整 财务要求可以同一个团队 调出团队和调入团队可以同一个 调整方案：以下代码注释掉
            // { validator: validatorTeam, trigger: "change" },
        ],
        allotInDate: [
            { required: true, message: '请选择调入时间!',trigger: 'change' },
            { validator: validatorInOrOutDate, trigger: "change" },
        ],
        bpmBizTitle:[
            { required: true, message: '请输入标题!' }
        ],
        },
        url: {
          add: "/api/erp/finance/capitalAllot/erpCapitalAllot/add",
          edit: "/api/erp/finance/capitalAllot/erpCapitalAllot/edit",
          queryById: "/api/erp/finance/capitalAllot/erpCapitalAllot/queryById",
          gainBillNo:"/api/erp/finance/capitalAllot/erpCapitalAllot/getBillNo"
        },
        userName: '',
         //代码生成后需手动设置流程编码
        flowCode: 'onl_erp_capital_allot',
        formUrl: "erp/finance/capitalAllot/modules/ErpCapitalAllotForm",
        formUrlMobile: "",
        dictOptions:{},
        superFieldList:[],
        columns:[
          {
            title:'调出团队',
            align:"center",
            dataIndex: 'teamId',
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['teamId'], text + '')
              }
            }
          },
        ]
      }
    },
    computed: {
       formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      //加载数据字典信息
      backUserInfo(data) {
        // this.model.applicant = data[0].orgDepart;//申请人单位
        this.model.departId = data[0].departmentId;//申请人部门
      },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
        this.model.proposer = this.userInfo().empId; //获取经办人id
        // this.model.proposerDeptId = this.userInfo().deptId;  //获取经办人部门id
        this.getBillNo();

      },
      //生成单据编号
      getBillNo () {
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            //that.model.billNo = res.result//单据编号
            this.$set(this.model,'billNo',res.result)
            //流程标题添加
            this.$set(this.model,'bpmBizTitle',this.userName + '-' + this.model.billNo);
          }
        })
      },
      getDate(date){
        var year = date.substr(0,4);//substr()是从0开始计算的
        var month = date.substr(5,2);//月份是0到11个月
        var day = date.substr(8,2);
        // alert();
        return year+"-"+month+"-"+day;
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },

      // 点击调出时间
      onAllotOutDateChange(date, dateString) {
        // this.model.allotOutDate = moment(date)
        this.$set(this.model, 'allotOutDate', dateString)
        this.allotOutDate = dateString
      },

      //点击调入时间
      onAllotInDateChange(date, dateString) {
        this.$set(this.model, 'allotInDate', dateString)
        this.allotInDate = dateString
      },

      // 重置调入调出时间
      resetDate(){
        this.$set(this.model,'allotOutDate',undefined)
        this.$set(this.model,'allotInDate',undefined)
        this.allotOutDate = null
        this.allotInDate = null
      },

      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        
        this.visible = true;

        // 判断是否有调入和调出日期
        
        if (this.model.allotOutDate) {
          this.allotOutDate = this.model.allotOutDate
          this.model.allotOutDate = moment(this.model.allotOutDate,'YYYY-MM-DD')
        }
        if (this.model.allotInDate) {
          this.allotInDate = this.model.allotInDate
          this.model.allotInDate = moment(this.model.allotInDate,'YYYY-MM-DD')
        }
        
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.allotOutDate = this.allotOutDate || null // 调出时间
        this.model.allotInDate = this.allotInDate || null // 调入时间
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#capitalContent',
          popTitle: '资金调拨申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
</style>